package game;

import chat.ChatBot;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import langen.TemplateGe_Library;

/**
 *  This class is part of the "World of Zuul" application. 
 *  "World of Zuul" is a very simple, text based adventure game.
 * 
 *  This class creates all rooms, creates the parser and starts
 *  the game.  It also evaluates and executes the commands that 
 *  the parser returns.
 * 
 * @author  Michael Kolling and David J. Barnes
 * @version 1.0 (Jan 2003)
 */
public class GameEngine
{
    public Parser parser;
    private Room currentRoom;
    private UserInterface gui;
    private Room outside, meadow, library, informatics,castle;
    private Person s2;//target
    private Role s1;//hunter
    public Random p=new Random();
    private TemplateGe_Library li=new TemplateGe_Library();
   

    /**
     * Constructor for objects of class GameEngine
     */
    public GameEngine()
    {
        parser = new Parser();
        createRooms();
        createRole();
    }
    
    public void createRole(){
        s1=new Role("hunter",30,null);
        s2=new Person("target",20,null);
        
        
    }


    public void setGUI(UserInterface userInterface)
    {
        gui = userInterface;
       
    }
    
    public Room radom_room(){
        Room s[]={outside, meadow, library, informatics,castle};
       
        return s[p.nextInt(s.length)];
    }
   

    /**
     * Print out the opening message for the player.
     */
    private void printWelcome()
    {
      
       String s="welcome to the boring game...\n";
        
        gui.get_panel().setVisible(true);
       s+="hi "+s1.get_name()+", you cannot find your friend now!!! Your goal is to find your friend ASAP.\nYou need to buy food to maintain the hp and get some cues from the characters.\n Good luck!\n" +currentRoom.getLongDescription();
       gui.println(s);

      
       

        
    }

    public void personalization(){

        String inputValue0 = JOptionPane.showInputDialog("Please input your name");
        s1.set_name(inputValue0);

        String inputValue1 =JOptionPane.showInputDialog("Please input the money you want");
   
        s1.set_info_money(Integer.parseInt (inputValue1));
        


    }

    /**
     * Create all the rooms and link their exits together.
     */
    private void createRooms()
    {



        
       

        // create the rooms with chatbot
        outside = new Room("outside the main entrance of the university","Sheldon","utils//outside.png","utils//outside_c.png");
        meadow = new Room("in the meadows","Nicholas","utils//meadows.png","utils//meadows_c.png");
        library = new Room("in the library","David","utils//lib.png","utils//lib_c.png");
        library.roombot().setLanguageGenerator(li);
        castle = new Room("in the Edinburgh meadows","Leanord","utils//castle.png","utils//castle_c.png");
        informatics = new Room("in the informatics forum","Strong Man","utils//informatics.png","utils//informatics_c.png");

        // initialise room exits
        outside.setExit("north", informatics);
        outside.setExit("south", castle);
        outside.setExit("west", library);

        library.setExit("east", outside);
        library.setExit("north", informatics);
        library.setExit("south", meadow);

        castle.setExit("west", meadow);
        castle.setExit("north", library);

        informatics.setExit("south", library);


        meadow.setExit("north", library);
        meadow.setExit("east", castle);





       
       


    
    }

    /**
     * Given a command, process (that is: execute) the command.
     * If this command ends the game, true is returned, otherwise false is
     * returned.
     */
  

    // implementations of user commands:
    /**
     * talk to chatbot
     */

    /**
     * Print out some help information.
     * Here we print some stupid, cryptic message and a list of the 
     * command words.
     */
    private void printHelp() 
    {
       
        gui.println("You can use direction stick to go where you want\n You can do commands in pariticular scene\n good luck: ");
    }

    /** 
     * Try to go to one direction. If there is an exit, enter the new
     * room, otherwise print an error message.
     */
    private void goRoom(Command command) 
    {
        

        String direction = command.getSecondWord();

        // Try to leave current room.
        Room nextRoom = currentRoom.getExit(direction);
        
        

        if (nextRoom == null)
        {
            gui.println("There is no door!");
        }
        else if(!process_goroom(nextRoom)){
            endGame(1);

        }
        else {
            
            

            if(s1.get_place().equals(s2.get_place()))//hunter gets the target
            {
                s2.set_icon(new ImageIcon("utils//target.png"));

                
                setback(currentRoom.get_pic_place(),currentRoom.get_pic_char(),s2.get_icon());//set background
                //gui.println("congratulations!! \n you find out your friend.");
                endGame(0);


                


            }
            else{

                 s2.set_place(this.radom_room());//target changes a room randomly
                 setback(currentRoom.get_pic_place(),currentRoom.get_pic_char(),s2.get_icon());//set background
                 

                 gui.println(currentRoom.getLongDescription());
                
                
            }
            
            
           
            

            
        }
    }

  private boolean process_goroom(Room nextRoom){
      currentRoom = nextRoom;
      s1.set_place(currentRoom);//hunter gets into the room
      gui.get_text().setText(currentRoom.get_chatbot_info());
      s1.set_hp(s1.get_hp()-20);//
      if(s1.get_hp()>0)
      {
          return true;
      }
      else
      {
          return false;
      }
  }

    private void setback(Icon place, Icon chatbot, Icon target){
       gui.getplace_label().setIcon(place);//set place picture

       gui.getchatbot_label().setIcon(chatbot);//set chatbot picture

       gui.gettar_label().setIcon(target);//set target pic

    }

    private void endGame(int flag)
    {
        String s;
        if(flag==0)
        {
          s="good job! you find your friend.\n do you want to play again?";
          //gui.game_over();
        }
        else
        {
            s="sorry, your hp is below zero, mession failed";
           // gui.game_over();
        }

        int i= JOptionPane.showConfirmDialog(null,s, "play again?",JOptionPane.YES_NO_OPTION);
       if(i==1)
        System.exit(0);
       else
       {
            this.createRole();//refresh the roles
            this.play();

        
       }
    }


     public void play()
    {
        
                  
          currentRoom = outside;  // start game outside
          s1.set_place(currentRoom);
          s2.set_place(meadow);
          personalization();
          printWelcome();
          setback(currentRoom.get_pic_place(),currentRoom.get_pic_char(),s2.get_icon());
          gui.get_text().setText(currentRoom.get_chatbot_info());
          
          
          
      

     }

    public void action(String commandLine){


            Command command = parser.getCommand(commandLine);
            processCommand(command);



}




    

     public void talk(Command command)
     {
         ChatBot c=currentRoom.roombot();
         String reply;
         String chatname=c.getName();
         if(chatname.equals(command.getSecondWord()))
         {
             reply=c.reply(command.getThirdWord());
             gui.println(c.getName()+": "+reply);
         }
         else
         {
             gui.println("sorry, chatbot is not here");
         }

     }

     public void buy_food()
     {
        if(s1.consume(1)){
            s1.set_hp(s1.get_hp()+p.nextInt(10)+s1.get_info_money()/10);//add hp

            gui.println("enjoy your meal and your hp is "+s1.get_hp()+" and your money is "+s1.get_info_money());

        }
        else{
            gui.println("you do not have enough money to buy food!");
        }


     }
     public void purchase(Command command)
     {
         String s;
         if(currentRoom.getShortDescription().equals(library.getShortDescription()))
         {
         if(s1.consume(1))
         {
             if(p.nextBoolean()){
                 s="thank you for you support and I saw your friend was at"+s2.get_place().getShortDescription()+" just now.";

             }
             else{
                 s="thank you for your support";
             }

         gui.println(s);
         }
         else
         {
         gui.println("you do not have enough money");

         }
         }
         else
         {
             gui.println("you cannot buy a book as you are not in a library");

         }

     }
     public void answer(Command command)
     {
         if(currentRoom.equals(informatics))
         {
             Object[] options = {"MIT","EDINBURGH","CAMBRIGE"};
        int response=JOptionPane.showOptionDialog(null, "which univeristy do you think is best at AI", "question_answer",JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        if (response==0){
            JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": i have no idea about your friend", "information", JOptionPane.DEFAULT_OPTION);
            
            
        }

            
        else if(response==2){
            JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": i have no idea about your friend", "information", JOptionPane.DEFAULT_OPTION);
           

         }
         else if(response==1)
         {
             JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": your friend may be in "+s2.get_place().getShortDescription(), "information", JOptionPane.DEFAULT_OPTION);
         }
         }
         else if(currentRoom.equals(castle))
         {
             Object[] options = {"AD 600","AD 800","2O12"};
        int response=JOptionPane.showOptionDialog(null, "when was first historical reference to Din Eidyn - a fortress on the rock?", "question_answer",JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

        if (response==1){
            JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": i have no idea about your friend", "information", JOptionPane.DEFAULT_OPTION);
            
            
        }
            
            
        else if(response==2){
            JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": i have no idea about your friend, maybe he is in 2012", "information", JOptionPane.DEFAULT_OPTION);
           

         }
         else if(response==0)
         {
             JOptionPane.showMessageDialog(null, currentRoom.roombot().getName()+": your friend may be in "+s2.get_place().getShortDescription(), "information", JOptionPane.DEFAULT_OPTION);
         }



         }
         else{
             //System.out.println(s2.get_place().getShortDescription());
             JOptionPane.showMessageDialog(null, "sorry , i have no question", "information", JOptionPane.DEFAULT_OPTION);
         }

     }
     public void status(Command command)
     {
         String name="Hi,"+s1.get_name();
         String place=s1.get_place().getLongDescription();
         String hp="your hp is "+s1.get_hp();
         String money="you have £ "+s1.get_info_money();
         String book= "you have "+s1.get_info_book()+"book(s)";
         String s=name+"\n"+place+"\n"+hp+"\n"+money+"\n"+book+"\n";


         gui.println(s);


     }

 public void processCommand(Command command)
    {
      

        if(command.isUnknown()) {
            gui.println("I don't know what you mean...\n you need to input like talk "+currentRoom.roombot().getName()+" +contens");
            
            
        }
        else{

        String commandWord = command.getCommandWord();
        if (commandWord.equals("help")) {
            printHelp();
        }
        else if (commandWord.equals("go")) {
            goRoom(command);
        }
        else if (commandWord.equals("quit")) {
            quit(command);
            
        }
        else if(commandWord.equals("talk")){
            talk(command);
            
        }
        else if(commandWord.equals("purchase")){
            purchase(command);
            
        }
        else if(commandWord.equals("answer_question")){
            answer(command);
            
        }
        else if(commandWord.equals("status")){
            status(command);
        }
        else if(commandWord.equals("play")){
            play();

        
        }
        else if(commandWord.equals("buy_food")){

            buy_food();
        }
        // else command not recognised.
        }
        
    }


 
 private void quit(Command command)
    {
        gui.println("are you sure you want to quit?");
    }
     
    static public void main(String[] argv) {
    	// create the game
    	GameEngine engine = new GameEngine();

        UserInterface gui = new UserInterface(engine);
		engine.setGUI(gui);
                gui.setVisible(true);
    	// invoke a method to play the game until the end

    	// clean up after the game ends
    }

}
